import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { ElMessage } from 'element-plus'
// import Store from '@/store'
const request = axios.create({
  baseURL: import.meta.env.VITE_GLOB_BASE_URL, // API 请求的默认前缀，可根据环境变量自行配置
  timeout: 60000, // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }

})

// 异常拦截处理器
const errorHandler = (error) => {
  ElMessage.error(error.message)
  if (error.response) {
    switch (error.response.status) {
      case 401:
        // 登录过期错误处理
        break
      case 500:
        // 服务器错误处理
        break
      default:
    }
  }
  return Promise.reject(error)
}

// 将参数转换成功 formdata 接收格式
function stringify(data) {
  const formData = new FormData()
  for (const key in data) {
    // eslint-disable-next-line no-prototype-builtins
    if (data.hasOwnProperty(key)) {
      if (data[key]) {
        if (data[key].constructor === Array) {
          if (data[key][0]) {
            if (data[key][0].constructor === Object) {
              formData.append(key, JSON.stringify(data[key]))
            } else {
              data[key].forEach((item, index) => {
                formData.append(key + `[${index}]`, item)
              })
            }
          } else {
            formData.append(key + '[]', '')
          }
        } else if (data[key].constructor === Object) {
          formData.append(key, JSON.stringify(data[key]))
        } else {
          formData.append(key, data[key])
        }
      } else {
        if (data[key] === 0) {
          formData.append(key, '0')
        } else {
          formData.append(key, '')
        }
      }
    }
  }
  return formData
}
// request interceptor
request.interceptors.request.use((config) => {
  /**
   * 如果token 存在，则给请求头加token
   */

  //  let formData = new FormData();
  //  config.data = config.data || {}
  //  Object.keys(config.data).forEach(key=>{
  //      formData.append(key, config.data[key]);
  //  })
  config.headers = {
    TOKEN: String(window.localStorage.getItem('token'))
    // X_CSRF_TOKEN: Store.getters.CSRF
    // 'Content-Type': 'application/json;charset=UTF-8'

  }
  // config.data = stringify(config.data)
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // console.log('00000',response)
  if (response.data.code == 'notAuth') {
    window.location.href = response.data.login_url
    // Router.push({
    //   name:'login'
    // })
    return
  }
  if (response.data.result == 'fail') {
    ElMessage.error(response.data.reason)
  }

  return response.data
}, errorHandler)

export default request
